import { selectors } from './config.js';
import { findCards } from './card-extractor.js';
import { extractGroups } from './group-extractor.js';
import { DateManager } from './date-manager.js';
import { navMenuManager } from './nav-menu-manager.js';
import { autoScrollInContainer } from '../../utils/scroll-helper.js';

// 创建日期管理器实例
const dateManager = new DateManager();

// 初始化观察器
dateManager.initObserver();

// 判断当前页面是否为抖音经营分析页面
export function isMatch() {
  console.log('开始检查页面匹配...');
  const root = document.querySelector(selectors.root);
  console.log('根节点匹配结果:', !!root, root);
  return !!root;
}

// 获取滚动容器选择器
export function getScrollContainer() {
  return '#pageScrollContent';  // 抖音页面的滚动容器ID
}

// 等待页面加载完成
async function waitForPageLoad() {
  return new Promise(resolve => {
    if (document.readyState === 'complete') {
      resolve();
    } else {
      window.addEventListener('load', resolve);
    }
  });
}

/**
 * 等待元素出现
 * @param {string} selector - 元素选择器
 * @param {number} timeout - 超时时间（毫秒）
 * @returns {Promise<Element|null>} 元素或null
 */
async function waitForElement(selector, timeout = 10000) {
  const startTime = Date.now();
  while (Date.now() - startTime < timeout) {
    const element = document.querySelector(selector);
    if (element) return element;
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  console.warn(`等待元素超时: ${selector}`);
  return null;  // 超时时返回null而不是抛出错误
}

// 提取单个页面的数据
async function extractPageData() {
  const root = document.querySelector(selectors.root);
  if (!root) {
    console.log('未找到根容器');
    return [];
  }
  console.log('找到根容器:', root);

  // 提取分组数据
  const groups = await extractGroups(root, findCards);
  
  // 如果没有找到任何分组，创建一个未分组
  if (groups.length === 0) {
    console.log('未找到任何分组，尝试创建未分组');
    const ungroupedCards = findCards(root);
    console.log('未分组卡片数:', ungroupedCards.length);
    
    if (ungroupedCards.length > 0) {
      groups.push({
        groupTitle: '未分组',
        cards: ungroupedCards
      });
      console.log('创建未分组，包含卡片数:', ungroupedCards.length);
    }
  } else {
    // 确保所有分组都有cards属性，即使为空数组
    groups.forEach(group => {
      if (!group.cards) {
        group.cards = [];
      }
    });
  }
  
  return groups;
}

// 提取抖音页面的分组与卡片数据
export async function extract(scope = 'current') {
  window._shouldStopExtraction = false; // 每次抓取前重置
  console.log('开始提取数据...', '抓取范围:', scope, 'window._extractionScope:', window._extractionScope);
  
  // 使用传入的scope参数，不再重复设置
  const currentScope = scope || 'current'; // 默认为当前页面
  console.log('当前使用的抓取范围:', currentScope);

  // 设置所有日期选择器
  await dateManager.setCustomDateRange(window._customDateRange.startDate, window._customDateRange.endDate);

  if (currentScope === 'current') {
    // 只抓取当前页面
    console.log('抓取当前页面数据...');
    // 执行全屏滚动以确保所有内容都加载
    await autoScrollInContainer(getScrollContainer());
    const pageGroups = await extractPageData();
    sendBatchExtracted(pageGroups, 0, true);
    return pageGroups;
  } else if (currentScope === 'all') {
    // 抓取所有页面
    console.log('开始抓取所有页面数据...');
    
    // 获取所有一级菜单项
    const mainMenuItems = navMenuManager.extractMenuItems();
    console.log('找到一级菜单项:', mainMenuItems);

    let allGroups = [];
    let batchIndex = 0;

    // 遍历一级菜单
    for (const mainMenuItem of mainMenuItems) {
      if (window._shouldStopExtraction) {
        if (allGroups.length > 0) {
          sendBatchExtracted(allGroups, batchIndex, true);
        } else {
          sendBatchExtracted([], batchIndex, true);
        }
        console.warn('抓取被用户中断（一级菜单）');
        return;
      }
      console.log('处理一级菜单:', mainMenuItem.text);
      
      // 点击一级菜单
      await navMenuManager.switchToMenuItem(mainMenuItem.text);
      await waitForPageLoad();
      
      // 执行全屏滚动以确保所有内容都加载
      await autoScrollInContainer(getScrollContainer());
      
      // 获取二级菜单
      const submenuItems = navMenuManager.extractSubmenuItems();
      console.log('找到二级菜单项:', submenuItems);

      // 新增：无二级菜单时直接抓取当前页面
      if (!submenuItems || submenuItems.length === 0) {
        await waitForElement(selectors.root);
        await autoScrollInContainer(getScrollContainer());
        const pageGroups = await extractPageData();
        const enrichedGroups = pageGroups.map(group => ({
          ...group,
          topic: mainMenuItem.text
        }));
        allGroups = allGroups.concat(enrichedGroups);
        if (allGroups.length >= 10) {
          sendBatchExtracted(allGroups, batchIndex, false);
          allGroups = [];
          batchIndex++;
        }
        continue; // 跳过后续 submenu 处理
      }

      // 遍历二级菜单
      for (const submenuGroup of submenuItems) {
        if (window._shouldStopExtraction) {
          if (allGroups.length > 0) {
            sendBatchExtracted(allGroups, batchIndex, true);
          } else {
            sendBatchExtracted([], batchIndex, true);
          }
          console.warn('抓取被用户中断（二级菜单）');
          return;
        }
        console.log('处理二级菜单组:', submenuGroup.groupTitle);
        
        // 遍历二级菜单中的每个子项
        for (const submenuItem of submenuGroup.items) {
          if (window._shouldStopExtraction) {
            if (allGroups.length > 0) {
              sendBatchExtracted(allGroups, batchIndex, true);
            } else {
              sendBatchExtracted([], batchIndex, true);
            }
            console.warn('抓取被用户中断（二级菜单项）');
            return;
          }
          console.log('处理二级菜单项:', submenuItem.text);
          
          // 点击二级菜单项
          await navMenuManager.switchToSubmenuItem(submenuGroup.groupTitle, submenuItem.text);
          await waitForPageLoad();
          
          // 等待数据加载
          await waitForElement(selectors.root);
          
          // 执行全屏滚动以确保所有内容都加载
          await autoScrollInContainer(getScrollContainer());
          
          // 提取当前页面数据
          const pageGroups = await extractPageData();
          
          // 为数据添加菜单信息
          const menuArr = [mainMenuItem.text];
          if (submenuGroup && submenuGroup.groupTitle) menuArr.push(submenuGroup.groupTitle);
          if (submenuItem && submenuItem.text) menuArr.push(submenuItem.text);
          // 过滤空字符串，避免--
          const topic = menuArr.filter(Boolean).join('-');
          const enrichedGroups = pageGroups.map(group => ({
            ...group,
            topic
          }));
          
          allGroups = allGroups.concat(enrichedGroups);
          
          // 每10个分组发送一次数据
          if (allGroups.length >= 10) {
            sendBatchExtracted(allGroups, batchIndex, false);
            allGroups = [];
            batchIndex++;
          }
          // 新增：每页后判断是否需要停止
          if (window._shouldStopExtraction) {
            console.warn('window._shouldStopExtraction:', window._shouldStopExtraction);
            if (allGroups.length > 0) {
              sendBatchExtracted(allGroups, batchIndex, true);
            } else {
              sendBatchExtracted([], batchIndex, true);
            }
            console.warn('抓取被用户中断（每页后）');
            return;
          }
        }
      }
    }

    // 发送剩余的数据
    if (allGroups.length > 0) {
      sendBatchExtracted(allGroups, batchIndex, true);
    } else {
      // 如果没有数据，发送空数组表示完成
      sendBatchExtracted([], batchIndex, true);
    }

    return;
  } else {
    console.error('未知的抓取范围:', currentScope);
    return [];
  }
}

// 封装批量发送消息
function sendBatchExtracted(data, batchIndex = 0, isLastBatch = true) {
  chrome.runtime.sendMessage({
    action: 'batchExtracted',
    batchIndex,
    isLastBatch,
    data,
    template: window._currentTemplateId
  });
}

// 获取商户信息
export async function getMerchantInfo() {
  // 等待商户信息元素加载
  const waitForMerchantInfo = async () => {
    const maxAttempts = 20; // 最多等待10秒
    for (let i = 0; i < maxAttempts; i++) {
      const accountIdElement = document.querySelector(".Sytgh .H8wwv span");
      const merchantNameElement = document.querySelector(".fuNk1");
      
      if (accountIdElement && merchantNameElement) {
        return {
          merchantId: accountIdElement.textContent.trim(),
          merchantName: merchantNameElement.textContent.trim(),
        };
      }
      
      await new Promise(resolve => setTimeout(resolve, 500));
    }
    throw new Error("等待商户信息超时");
  };

  const data = await waitForMerchantInfo();
  console.log("抖音生意经 - 获取到商户信息:", data);
  return data;
}

// 判断当前页面是否为抖音经营分析页面
export function isDouyinPage() {
  return window.location.href.includes('douyin.com');
}

// 导出日期管理器
export { dateManager };
